//
//  ZGLSubscribeCell.m
//  Faker
//
//  Created by dllo on 15/10/29.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "ZGLSubscribeCell.h"
#import "ZGLSubscribeCollectionViewViewCell.h"
#import "ZGLAddOptionsCell.h"

@interface ZGLSubscribeCell () <UICollectionViewDataSource ,UICollectionViewDelegate> {
    NSString *plistPath;
}

@property (nonatomic, strong) UICollectionView *subscribeCollectionView;
@property (nonatomic, strong) NSMutableDictionary *dic;

@end

@implementation ZGLSubscribeCell

- (void)dealloc {
    _subscribeCollectionView.delegate = nil;
    _subscribeCollectionView.dataSource = nil;
}

//保存数据到NSUserDefaults
- (void)saveNSUserDefaultsWith:(NSMutableArray *)modelArr;
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:modelArr forKey:@"currentArr"];
    //这里建议同步存储到磁盘中，但是不是必须的
    [userDefaults synchronize];
}
//从NSUserDefaults中读取数据
- (void)readNSUserDefaults {
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    _optionsArr = [userDefaultes arrayForKey:@"startArr"].mutableCopy;
}




- (void)createSubscribeCollectionView {
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.itemSize = CGSizeMake(ScaleX * 375 / 3, ScaleX * 375 / 3);
    flow.minimumInteritemSpacing = 0;
    flow.minimumLineSpacing = 0;
    flow.scrollDirection = 0;

    self.subscribeCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0,ScaleX * 375, ScaleX * 375) collectionViewLayout:flow];
    self.subscribeCollectionView.delegate = self;
    self.subscribeCollectionView.dataSource = self;
    self.subscribeCollectionView.backgroundColor = [UIColor whiteColor];
    [self.subscribeCollectionView registerClass:[ZGLSubscribeCollectionViewViewCell class] forCellWithReuseIdentifier:@"ZGLSubscribeCell_ZGLSubscribeCollectionViewViewCell"];
    [self.subscribeCollectionView registerClass:[ZGLAddOptionsCell class] forCellWithReuseIdentifier:@"ZGLSubscribeCell_ZGLAddOptionsCell"];
    //此处给其增加长按手势，用此手势触发cell移动效果
    UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
    [self.subscribeCollectionView addGestureRecognizer:longGesture];
    [self.contentView addSubview:self.subscribeCollectionView];
}


- (void)handlelongGesture:(UILongPressGestureRecognizer *)longGesture {
    //判断手势状态
    switch (longGesture.state) {
        case UIGestureRecognizerStateBegan:{
            //判断手势落点位置是否在路径上
            NSIndexPath *indexPath = [self.subscribeCollectionView indexPathForItemAtPoint:[longGesture locationInView:self.subscribeCollectionView]];
            if (indexPath == nil) {
                break;
            }
            //在路径上则开始移动该路径上的cell
            [self.subscribeCollectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
        }
            break;
        case UIGestureRecognizerStateChanged:
            //移动过程当中随时更新cell位置
            [self.subscribeCollectionView updateInteractiveMovementTargetPosition:[longGesture locationInView:self.subscribeCollectionView]];
            break;
        case UIGestureRecognizerStateEnded:
            //移动结束后关闭cell移动
            
            [self.subscribeCollectionView endInteractiveMovement];
            break;
        default:
            [self.subscribeCollectionView cancelInteractiveMovement];
            break;
    }
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self readNSUserDefaults];
        self.dic = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
        [self createSubscribeCollectionView];
    }
    return self;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    //返回YES允许其item移动
    if (self.optionsArr.count == indexPath.item) {
        return NO;
    } else {
        return YES;
    }
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath {
    //交换资源数组中移动item和目标位置item的资源位置
    if (destinationIndexPath.item == _optionsArr.count) {
        
    } else {
        [self.optionsArr exchangeObjectAtIndex:sourceIndexPath.item withObjectAtIndex:destinationIndexPath.item
         ];
        [self saveNSUserDefaultsWith:_optionsArr];
        [self.subscribeCollectionView reloadData];
    }
}

- (NSIndexPath *)collectionView:(UICollectionView *)collectionView targetIndexPathForMoveFromItemAtIndexPath:(NSIndexPath *)originalIndexPath toProposedIndexPath:(NSIndexPath *)proposedIndexPath {
    if (proposedIndexPath.item == _optionsArr.count) {
        return originalIndexPath;
    } else {
        return proposedIndexPath;
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self.subscribeCollectionView setFrame:CGRectMake(0, 0, ScaleX * 375, ((self.optionsArr.count + 1) / 3 + 1) * ScaleY * 125)];
    self.subscribeCollectionView.backgroundColor = backColor;
}

- (void)setOptionsArr:(NSMutableArray *)optionsArr {
    if (_optionsArr != optionsArr) {
        _optionsArr = optionsArr;
    }
    [self.subscribeCollectionView reloadData];
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.optionsArr.count == 0) {
        return 1;
    } else {
        return self.optionsArr.count + 1;
    }
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item >= 0 && indexPath.item < self.optionsArr.count) {
        ZGLSubscribeCollectionViewViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZGLSubscribeCell_ZGLSubscribeCollectionViewViewCell" forIndexPath:indexPath];
        cell.backgroundColor = foreColor;
        cell.titleLabel.textColor = artiColor;
        cell.dic = self.optionsArr[indexPath.item];
        return cell;
    } else {
        ZGLAddOptionsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZGLSubscribeCell_ZGLAddOptionsCell" forIndexPath:indexPath];
        cell.backgroundColor = foreColor;
        cell.titleLabel.textColor = artiColor;
        return cell;
    }
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == self.optionsArr.count) {
        [self.delegate pushDetailsVCWith:[self judgeIndexPath:indexPath] with:nil];
    } else {
        [self.delegate pushDetailsVCWith:[self judgeIndexPath:indexPath] with:self.optionsArr[indexPath.item]];
    }
}

- (BOOL)judgeIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == self.optionsArr.count) {
        return YES;
    } else {
        return NO;
    }
    
}





- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
